package com.hzgj.bcl.soa.command;

import com.google.common.collect.Maps;
import com.hzgj.bcl.redis.RedisClient;
import com.hzgj.bcl.util.IocContext;
import com.hzgj.bcl.util.lang.StrKit;
import redis.clients.jedis.Tuple;

import java.util.Map;
import java.util.Set;

import static com.hzgj.bcl.stats.TimeCounter.oneMinute;

/**
 * Created by Administrator on 2016/9/2.
 */
public abstract class InvokeDyCommand extends BaseCommand {
    protected RedisClient redisClient;
    /**
     * //TODO
     * 需要和<code>RemoteSendStats统一</code>
     */
    public static long intervalSpan = 1;

    @Override
    public String invoke(CommandOptions commandOptions) {
        String[] service_param = commandOptions.params.get("service");
        String[] method_param = commandOptions.params.get("method");
        String[] hostPort_param = commandOptions.params.get("hostPort");
        String[] time_param = commandOptions.params.get("time");
        String service;
        if (service_param == null) {
            throw new RuntimeException("can't get parameter service.");
        }
        service = service_param[0];

        String method;
        if (method_param == null) {
            throw new RuntimeException("can't get parameter method.");
        }
        method = method_param[0];

        String time;
        if (time_param == null) {
            throw new RuntimeException("can't get parameter time.");
        }
        time = time_param[0];

        long target = Long.parseLong(time) + intervalSpan * oneMinute;

        String hostPort = null;
        if (hostPort_param != null) {
            hostPort = hostPort_param[0];
        }

        String baseKey = service + "_" + method;
        if (StrKit.notBlank(hostPort)) {
            baseKey += "_" + hostPort.replace(":", "_");
        }
        return handleDyData(baseKey, target);
    }

    abstract String handleDyData(String baseKey, long target);

    protected Map<String, Object> buildTuple(Set<Tuple> tuples, String name, long time) {
        Map<String, Object> map = Maps.newHashMap();
        tuples.forEach(tuple -> {
            String member = tuple.getElement();
            map.put("name", name);
            map.put("value", member.split("_")[0]);
            map.put("time", time);
        });
        return map;
    }

    @Override
    public void start() {
        redisClient = IocContext.applicationContext.getBean(RedisClient.class);
    }
}
